<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\V1\Traits\CouponTrait;
use App\Models\FreeCode;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class CouponController extends Controller
{
    use CouponTrait;

    //前台用户使用
    public function freeCouponByCode(Request $request)
    {
        $freeCode = FreeCode::query()->where('code', $request->input('code'))->first();
        if ($freeCode instanceof FreeCode) {
            if (Carbon::now()->gt($freeCode->expired_at)) {
                return response()->json(['code' => 1001, 'message' => '兑换码已过期']);
            }
            $user = Auth::user();
            $this->addCoupon($user, 'free', '兑换码咖啡券', $freeCode->expired_at->toDateTimeString());
        }
        return response()->json(['code' => 1002, 'message' => '无效兑换码']);
    }

    //后台用户操作
    public function getFreeCode(Request $request)
    {
        $codes = [];
        for ($i = 1; $i <= $request->input('sum'); $i ++) {
            $codes[] = FreeCode::create([
                'code' => $this->getUniqueCode(),
                'expired_at' => $request->input('expired_at'),
            ]);
        }

        return response()->json(['code' => 1, 'data' => $codes]);
    }

    //后台用户操作
    public function getUniqueCode()
    {
        do {
            $code = str_random(8);
        } while (FreeCode::query()->where('code', $code)->first() instanceof FreeCode);

        return $code;
    }

    public function getAllFreeCode()
    {
        $codes = FreeCode::query()->where('expired_at', '>', Carbon::now())->where('is_used', false)->get();

        return response()->json(['code' => 1, 'data' => $codes]);
    }
}
